import { queryCurrent, query as queryUsers, fetchShopList } from '@/services/user';
import db from '@/utils/localstorage';
import { history } from 'umi';
const SuperAdminRole = ['admin', 'enterprise_admin']
const UserModel = {
  namespace: 'user',
  state: {
    currentUser: {},
    userVenueList: [],
    currentVenue: null
  },
  effects: {
    *fetch(_, { call, put }) {
      const response = yield call(queryUsers);
      yield put({
        type: 'save',
        payload: response,
      });
    },
    *fetchVenueList({ payload }, { call, put }) {
      const response = yield call(fetchShopList, payload);
      if (response.code === 0) {
        const dbVenue = db.get("venue")
        const venueOne = response.data?.find(item => item.id === dbVenue?.id && dbVenue.id !== '101')
        if (venueOne) {
          yield put({
            type: 'common',
            payload: {
              currentVenue: venueOne
            },
          });
          db.save('venue', venueOne);
        } else {
          const roles = db.get("roles");
          let isSuperAdmin;
          if (roles) {
            isSuperAdmin = roles.find(item => SuperAdminRole.includes(item.roleSign))
          }
          if (!isSuperAdmin) {
            yield put({
              type: 'common',
              payload: {
                currentVenue: response.data?.[0] ?? {}
              },
            });
            db.save('venue', response.data?.[0] ?? {});
          }
        }
        yield put({
          type: 'common',
          payload: {
            userVenueList: response.data,
          },
        });
      }
    },

    *fetchCurrent(_, { call, put }) {
      const response = yield call(queryCurrent);
      if (typeof response == 'boolean') {
        if (response) {
          yield put({
            type: 'saveCurrentUser',
            payload: db.get("user"),
          });
        } else {
          history.push(`/user/login`);
        }
      } else {
        history.push(`/user/login`);
      }
    },
  },
  reducers: {
    common(state, action) {
      return {
        ...state,
        ...action.payload,
      };
    },
    saveCurrentUser(state, action) {
      return { ...state, currentUser: action.payload || {} };
    },

    changeNotifyCount(
      state = {
        currentUser: {},
      },
      action,
    ) {
      return {
        ...state,
        currentUser: {
          ...state.currentUser,
          notifyCount: action.payload.totalCount,
          unreadCount: action.payload.unreadCount,
        },
      };
    },
  },
};
export default UserModel;
